package com.guigu.controller;

import cn.hutool.core.bean.BeanUtil;
import com.guigu.domain.dto.SubjectCategoryDTO;
import com.guigu.domain.entity.SubjectCategory;
import com.guigu.result.Result;
import com.guigu.service.ISubjectCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 刷题模块
 */
@RestController
@RequestMapping("/subject")
@Slf4j
public class SubjectController {

    @Resource
    private ISubjectCategoryService ISubjectCategoryService;

    @PostMapping("/add")
    public Result<Boolean> addSubjectCategory(@RequestBody SubjectCategoryDTO subjectCategoryDTO) {
        SubjectCategory subjectCategory = BeanUtil.toBean(subjectCategoryDTO, SubjectCategory.class);
        this.ISubjectCategoryService.save(subjectCategory);
        return Result.ok("新增分类成功");
    }

    @PostMapping("/update")
    public Result<Boolean> updateSubjectCategory(@RequestBody SubjectCategoryDTO subjectCategoryDTO) {
        SubjectCategory subjectCategory = BeanUtil.toBean(subjectCategoryDTO, SubjectCategory.class);
        this.ISubjectCategoryService.save(subjectCategory);
        return Result.ok("新增分类成功");
    }


    @PutMapping("/delete/{id}")
    @ApiOperation(value = "删除题目分类")
    public Result<Boolean> delete(@PathVariable Integer id) {
        try {
            this.ISubjectCategoryService.deleteSubjectCategory(id);
            return Result.ok("删除成功");
        } catch (Exception e) {
            log.error("SubjectController.delete.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 查询分类
     *
     * @param subjectCategoryDTO
     * @return
     */
    @PostMapping("/queryCategory")
    @ApiOperation(value = "查询题目分类")
    public Result<List<SubjectCategoryDTO>> querySubjectCategory(@RequestBody SubjectCategoryDTO subjectCategoryDTO) {
        try {
            SubjectCategory subjectCategory = BeanUtil.toBean(subjectCategoryDTO, SubjectCategory.class);
            List<SubjectCategory> subjectCategoryList = ISubjectCategoryService.queryCategory(subjectCategory);
            List<SubjectCategoryDTO> subjectCategoryDTOList = new ArrayList<>();
            subjectCategoryList.forEach(subjectCategory1 -> {
                SubjectCategoryDTO categoryDTO = BeanUtil.toBean(subjectCategory1, SubjectCategoryDTO.class);
                subjectCategoryDTOList.add(categoryDTO);
            });
            return Result.ok(subjectCategoryDTOList);
        } catch (Exception e) {
            log.error("SubjectController.queryPrimaryCategory.error:{}", e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
    }


}

